package springcloud.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import springcloud.service.PaymentHystrixService;


@RestController
@Slf4j
@DefaultProperties(defaultFallback = "paymentGlobalFallback")
public class OrderHystrixController {
    @Autowired
    private PaymentHystrixService paymentHystrixService;

    //当没有指名fallbackMethod参数时 出错会默认找全局默认的defaultFallback方法
    @HystrixCommand
    @GetMapping("/consumer/payment/hystrix/{id}")
    public String paymentInfo(@PathVariable("id") Integer id){
        String result = paymentHystrixService.paymentInfo(id);
        log.info("*****result: ",result);
        return result;
    }
/*注意此时配置的Hystrix是要在OpenFeign连接后才会默认允许
服务端配置了2秒的延迟 如果没有配置connect-timeout 与 read-timeout时间 OpenFeign会默认为1秒 然后会连接失败
即使此时配置了Hystrix的峰值时间为3秒
在配置了connect-timeout 与 read-timeout时间为5秒后	才会允许Hystrix的降级服务*/
    @GetMapping("/consumer/payment/hystrix/timeout/{id}")
    @HystrixCommand(fallbackMethod = "paymentInfoTimeoutHandle",commandProperties = {
            //设置自身调用超过时间的峰值 峰值内可以正常运行
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
    })
    public String paymentInfoTimeout(@PathVariable("id") Integer id){
        String result = paymentHystrixService.paymentInfoTimeout(id);
        log.info("*****result: ",result);
        return result;
    }
    public String paymentInfoTimeoutHandle(Integer id) {
        return "80 访问超时";
    }

    //以下是全局异常处理
    public String paymentGlobalFallback(){
        return "全局异常处理信息";
    }
}
